﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using Out.Service.HttpClients;
using OutDbContext;

namespace Out.Service.Services
{
    public class BizDoctor : IDisposable
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(BizDoctor));
        private readonly GdsfybjyWeiXinEntities _ctx;
        private readonly string _deptId;
        private readonly string _doctorId;

        public BizDoctor()
        {
            _ctx = new GdsfybjyWeiXinEntities();
        }

        public BizDoctor(string deptId, string doctorId = "")
        {
            _ctx = new GdsfybjyWeiXinEntities();
            _doctorId = doctorId;
            _deptId = deptId;
        }

        /// <summary>
        /// 获取科室内所有医生
        /// </summary>
        /// <returns></returns>
        public List<Doctor> GetAll()
        {
            var doctors = _ctx.Doctors.Where(x => x.RecStatus == 1 && x.DeptId == _deptId);

            var resDoctors = doctors
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return resDoctors;
        }

        /// <summary>
        /// 获取单个医生信息
        /// </summary>
        /// <returns></returns>
        public Doctor Get()
        {
            var doctor = _ctx.Doctors.FirstOrDefault(x => x.DeptId == _deptId && x.DoctorId == _doctorId);
            return doctor;
        }

        /// <summary>
        /// 搜索医生
        /// </summary>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        public List<Doctor> Search(string keyword)
        {
            var doctors = _ctx.Doctors.Where(x => x.RecStatus == 1 && x.DoctorName.Contains(keyword));

            var resDoctors = doctors
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return resDoctors;
        }

        /// <summary>
        /// 获取排班分时列表
        /// </summary>
        /// <param name="regDate">挂号日期</param>
        /// <param name="regType">号类</param>
        /// <param name="timeSlice">时段</param>
        /// <returns></returns>
        public List<ScheduleTimePoint> GetScheduleTimePoints(string regDate, string regType, string timeSlice)
        {
            var timePoints = new List<ScheduleTimePoint>();

            //执行获取排班分时信息
            var request = new GetTimeRegInfoRequest();
            request.DeptId = _deptId;
            request.DoctorId = _doctorId;
            request.RegDate = regDate;
            request.RegType = regType;
            request.TimeSlice = timeSlice;

            GetTimeRegInfoResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetTimeRegInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetTimeRegInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班分时Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return timePoints;
            }

            if (response.ResultCode != "0")
            {
                return timePoints;
            }

            timePoints = response.TimeRegList.Select(x => new ScheduleTimePoint
            {
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                TotalCount = x.TotalCount,
                LeaveCount = x.LeaveCount,
                SqNo = x.SqNo
            }).ToList();

            return timePoints;
        }

        public void Dispose()
        {
            _ctx.Dispose();
        }
    }

    public class ScheduleTimePoint
    {
        /// <summary>
        ///     分时开始时间，格式：HH:mm
        /// </summary>
        public string StartTime { get; set; }

        /// <summary>
        ///     分时结束时间，格式：HH:mm
        /// </summary>
        public string EndTime { get; set; }

        /// <summary>
        ///     可预约号源数
        /// </summary>
        public string TotalCount { get; set; }

        /// <summary>
        ///     剩余号源数
        /// </summary>
        public string LeaveCount { get; set; }

        /// <summary>
        ///     分时序号
        /// </summary>
        public string SqNo { get; set; }
    }
}